from flask import Flask,request
from strong_mysql import TodoStrongMysql
from todo import Todo

storage = TodoStrongMysql()
#创建一个服务器程序的实例
app = Flask(__name__)

app.config['JSON_AS_ASCII'] = False


@app.route('/')
def index():
    return "<h1>Hello,Flask</h1>"


@app.route('/todos',methods = ['GET'])
def get_list():
    return {'title':[x.__dict__ for x in storage.get_list()]}

@app.route('/todos',methods = ['POST'])
def craet_todo():
    if 'title' not in request.form:
        return '参数错误，必须提供title参数',400
    todo =storage.create(request.form['title'])
    return todo.__dict__


@app.route('/todos/mark_complete',methods = ['GET'])
def mark_completed():
    if 'todo_id' not in request.args:
        return '参数错误，必须提供title参数',400
    todo_id = int(request.args['todo_id'])
    todo = storage.mark_completed(todo_id)
    if todo is not None:
        return todo.__dict__
    else:
        return  f'todo not found, todo_id={todo_id}',404
@app.route("/todos/del_todo_id", methods=['GET'])
def del_todo_id():
    if 'todo_id' not in request.args:
        return '参数错误，必须提供 id 参数', 400
    todo_id = int(request.args['todo_id'])
    todo = storage.del_todos(todo_id)
    return todo.__dict__
if (__name__) == "__main__":
    # app.run()
    app.run(host='127.0.0.1', port=80, debug=True, threaded=True)